<?php


namespace app\service\keywordMonitor;


use app\exception\BadSysSettingException;
use app\model\Model;
use app\model\SysSetting;
use GuzzleHttp\Client;
use think\facade\Log;

class FiveMonitor implements BaseMonitor
{
    private $baseUrlV1 = 'http://apis.5118.com/morerank/';
    private $website;
    private $keyword;
    private $sellerId;
    private $checkrow = 100;

    public function __construct($sellerId,$website,$keyword)
    {
        $this->setSellerId($sellerId);
        $this->setWebsite($website);
        $this->setKeyword($keyword);
    }


    /**
     * @throws \app\exception\ModelException
     * @throws BadSysSettingException
     */
    public function baidumobile()
    {
        // baidumobile
        $key = $this->getApiKey(['seller_id' => $this->sellerId,'title'=>'five_baidu_mob']);
        if(empty($key)){
            throw new BadSysSettingException('百度PC配置错误,请检查');
        }
        return $this->getMonitorData($key['value'],'baidumobile');
    }

    /**
     * @throws \app\exception\ModelException
     * @throws BadSysSettingException
     */
    public function baidupc()
    {
        $key = $this->getApiKey(['seller_id' => $this->sellerId,'title'=>'five_baidu_pc']);
        if(empty($key)){
            throw new BadSysSettingException('百度PC配置错误,请检查');
        }
        return $this->getMonitorData($key['value'],'baidupc');
    }

    /**
     * @throws \app\exception\ModelException
     * @throws BadSysSettingException
     */
    public function haosoupc()
    {
        // haosou
        $key = $this->getApiKey(['seller_id' => $this->sellerId,'title'=>'haosou_pc']);
        if(empty($key)){
            throw new BadSysSettingException('百度PC配置错误,请检查');
        }
        return $this->getMonitorData($key['value'],'haosou');
    }

    /**
     * @throws \app\exception\ModelException
     * @throws BadSysSettingException
     */
    public function sougoumobile()
    {
        // sogomobile
        $key = $this->getApiKey(['seller_id' => $this->sellerId,'title'=>'sougou_mob']);
        if(empty($key)){
            throw new BadSysSettingException('百度PC配置错误,请检查');
        }
        return $this->getMonitorData($key['value'],'sogomobile');
    }

    /**
     * 发送请求
     * @param $key
     * @param $path
     */
    public function getMonitorData($key,$path)
    {
        $url = $this->baseUrlV1 . $path;
        $option = [
            'headers' => [
                'Authorization' => 'APIKEY '. $key,
                'Content-type'  => 'application/x-www-form-urlencoded'
            ],
            'form_params' => [
                'url' => $this->website,
                'keywords' => $this->keyword,
                'checkrow' => $this->checkrow,
            ],

        ];
        $response = $this->sendPostRequest($url,$option);
        if ($response['errcode'] != 0 && $response['errmsg'] != "") {
            return $response;
        }
        $taskId = $response['data']['taskid'];
        if(empty($taskId)){
            return jsonReturn(-34,'数据采集失败,请重新尝试');
        }
        Log::record("taskId:$taskId");
        file_put_contents('./task',$taskId);
        $dataRes  = $this->sendPostRequest($url,[
            'form_params' => [
                'taskid' => $taskId,
            ],
            'headers' => [
                'Authorization' => 'APIKEY '. $key
            ]
        ]);
        if($dataRes['errcode'] == "200104" &&  $dataRes['errmsg'] =="数据采集中"){
            while(true){
                sleep(5);
                $tmpRes = $this->sendPostRequest($url,[
                    'form_params' => [
                        'taskid' => $taskId,
                    ],
                    'headers' => [
                        'Authorization' => 'APIKEY '. $key
                    ]
                ]);
                if ($tmpRes['errcode'] == 0) {
                    return $tmpRes;
                }
            }
        }else{
            return $dataRes;
        }
    }

    public function sendPostRequest($url,$option)
    {
        $client = new Client();
        $response = $client->post($url,$option);
        return json_decode($response->getBody()->getContents(),true);
    }

    public function setWebsite($website)
    {
        $this->website = $website;
    }

    public function setKeyword($keyword)
    {
        $this->keyword = $keyword;
    }

    public function setSellerId($sellerId)
    {
        $this->sellerId = $sellerId;
    }

    /**
     * 获取对应配置
     * @throws \app\exception\ModelException
     */
    public function getApiKey($param)
    {
        $SysSetting = new SysSetting();
        return $SysSetting->getSysSetting($param)['data'];
    }
}